﻿using System.Text.RegularExpressions;

namespace zijian666.Updater;

/// <summary>
/// 各种扩展方法
/// </summary>
internal static partial class MethodExtensions
{
    // 用于匹配 ${var} 或 %var% 或 $(var) 形式的变量
    [GeneratedRegex(@"\$\{(?<var>[a-zA-Z_][a-zA-Z0-9_]*)\}|%(?<var>[a-zA-Z_][a-zA-Z0-9_]*)%|\$\((?<var>[a-zA-Z_][a-zA-Z0-9_]*)\)", RegexOptions.Compiled)]
    private static partial Regex MatchVariablePlaceholders();

    /// <summary>
    /// 替换字符串中的变量占位符，变量格式支持 ${var}、%var%、$(var)
    /// </summary>
    /// <returns></returns>
    public static string ReplacePlaceholders(this string str, Func<string, string?> func)
    {
        return MatchVariablePlaceholders().Replace(str, match =>
        {
            var name = match.Groups["var"].Value;
            return func(name) ?? match.Value;
        });
    }

    /// <summary>
    /// 将两个异步函数链接起来，前一个函数的结果作为后一个函数的输入
    /// </summary>
    public static Func<string, Task<string>>? Link(this Func<string, Task<string>>? task, Func<string, Task<string>>? next)
    {
        if (task == null)
        {
            return next;
        }
        if (next == null)
        {
            return task;
        }
        return async str => await next(await task(str));
    }
}
